<template>
  <div class="register_box knife_container">
    <div class="forms">
      <div class="logo_img_box">
        <span class="logo_img">
          <img src="../../images/knife_logo.png" alt="">
        </span>
        <h2 class="memberTit">--欢迎您注册为刀具联盟会员--</h2>
      </div>

      <step :stage="forgetStage" :content="['验证手机号', '设置新密码']"></step>

      <template v-if="forgetStage === 'one'">
        <!-- 手机号码和验证 v-show="!mobileError.status"-->
        <div class="form-box">
          <div class="invite-person" v-if="!!username">
            <span class="title">您的推荐人 </span><span class="invite-name">{{username}}</span>
          </div>
          <div class="form-item">
            <!-- <span class="form-span">手机号码</span> -->
            <input v-model="forgetForm.mobile" class="form-input el-input__inner" type="text" ref='mobile' placeholder="请输入11位手机号码" @keyup="validateMethod(forgetForm.mobile,'mobile')" />
            <p class="error" v-show="!mobileError.status && mobileError.text.length > 0"><i class="el-icon-warning"></i>{{mobileError.text[0]}}</p>
          </div>
          <div class="form-item">
            <!-- <span class="form-span">短信验证码</span> -->
            <div class="validate-box">
              <input
                v-model="forgetForm.imgVerifyCode"
                class="form-input el-input__inner"
                style="width: 230px" type="text" 
                auto-complete="off" 
                placeholder="请输入图形验证码" 
                ref="refcode" 
                @keyup="validateMethod(forgetForm.imgVerifyCode,'imgVerifyCode')"
              />
            <img v-show="codeImg" class="valicode-item imgCode" :src="codeImg" @click="verifyImage"/>
            </div>
            <p class="error" v-show="!codeError.status && codeError.text.length > 0"><i class="el-icon-warning"></i>{{codeError.text[0]}}</p>
          </div>
          <div class="form-item">
            <!-- <span class="form-span">短信验证码</span> -->
            <div class="validate-box">
              <input
                v-model="forgetForm.code"
                class="form-input el-input__inner"
                style="width: 230px" type="text" 
                auto-complete="off" 
                placeholder="请输入6位验证码" 
                ref="refcode" 
                @keyup="validateMethod(forgetForm.code,'code')"
              />
            <button class="valicode-item valiCode" @click="getCode" :class="{'disabled not_allow': !ableSendCode}" :disabled="!ableSendCode"> {{validateText}}</button>
            </div>
            <p class="error" v-show="!codeError.status && codeError.text.length > 0"><i class="el-icon-warning"></i>{{codeError.text[0]}}</p>
          </div>
          <button class="sureBtn" :class="{'active': computedMobile}" :disabled="!computedMobile" @click="forgetMobile">下一步</button>
        </div>
      </template>

      <template v-if="forgetStage === 'two'">
        <!-- 用户名和密码 -->
        <div class="form-box" ref="registerRef">
          <div class="form-item">
            <input
              class="form-input el-input__inner"
              v-model="forgetForm.password"
              type="password"
              placeholder="请输入密码"
              ref="refpwd" 
              @keyup="blurValidateMethod($event, 'password')" 
              auto-complete="off" 
              clearable
            />
            <p class="error" v-show="!passwordError.status && passwordError.text.length > 0">
              <i class="el-icon-warning"></i>登录密码错误!<br>
              <em class="B-error" v-for="text in passwordError.text">
                {{text}}</br>
              </em>
            </p>
          </div>
          <div class="form-item">
            <!-- <span class="form-span">确认密码</span> -->
            <input class="form-input el-input__inner" v-model="forgetForm.repwd" type="password"  placeholder="请再次输入密码" @keyup="validateRePwd($event)" auto-complete="off" clearable/>
            <p class="error" v-show="!repwdError.status && repwdError.text.length"><i class="el-icon-warning"></i>{{repwdError.text[0]}}</p>
          </div>
          <button class="sureBtn" :class="{'active': computedName}" :disabled="!computedName" @click="pwSubmit">提交</button>
        </div>
      </template>
    </div>

    <!-- 注册成功 -->
    <el-dialog title="" :visible.sync="reloadPW_succeed" width="480px" :show-close="false" center>
      <div class="dialog-certinfo-wrapper">
        <p class="info-content">密码重置成功</p>
        <!-- <span class="small-content">XXXX</span> -->
      </div>
      <span slot="footer" class="dialog-footer">
        <router-link class="btn-submit" :to="{name: 'Login'}">立即登录</router-link>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {PHONE} from '@/config/regex'
import {Form, FormItem, Button, Input, Upload, Checkbox, Cascader, Dialog} from 'element-ui'
import {step} from '@/components/index'
import {sendCode, verifyImage, reloadPW, mobileValidate} from '@/service/get-data'
import {mapState} from 'vuex'
export default {
  components: {
    elForm: Form,
    elFormItem: FormItem,
    elButton: Button,
    elInput: Input,
    elUpload: Upload,
    elCheckbox: Checkbox,
    elCascader: Cascader,
    elDialog: Dialog,
    step
  },
  data () {
    return {
      reloadPW_succeed: false, // 重置密码成功的弹窗
      forgetForm: {
        mobile: '', // 注册手机号码
        code: '', // 短信验证码
        imgVerifyCode: '', // 图形验证码
        newPassword: '', // 新密码
        password: ''// 确认新密码
      },
      time: 0,
      isSend: false, // 短信是否发送
      codeImg: '', // 图形验证码base64
      mobileError: { // 手机号码验证
        status: false,
        text: []
      },
      codeError: { // 验证码
        status: false,
        text: []
      },
      invitedCodeError: { // 邀请码
        status: false,
        text: []
      },
      usernameError: { // 用户名
        status: false,
        text: []
      },
      passwordError: { // 密码
        status: false,
        text: []
      },
      repwdError: { // 确认密码
        status: false,
        text: []
      },
      forgetStage: 'one', // one 手机号验证 two 用户名密码设置 three 企业信息
      strategy: {
        mobile: {
          zero: '手机不能为空',
          rules: [PHONE],
          texts: ['手机格式不正确']
        },
        code: {
          zero: '请填写验证码',
          rules: [/^\d{6}$/],
          texts: ['长度为6']
        },
        imgVerifyCode: {
          zero: '请输入图形验证码',
          rules: [/^\d*$/],
          texts: ['不能为空']
        },
        invitedCode: {
          rules: [/^\S{6}$/],
          texts: ['长度为6']
        },
        username: {
          zero: '请输入用户名',
          rules: [/^\S{4,12}$/, /^[0-9A-Za-z\u4e00-\u9fa5]{4,12}$/],
          texts: ['4～12个非空字符', '可由汉字、大小写字母或数字组成']
        },
        password: {
          zero: '请输入密码',
          rules: [/^\S{6,20}$/, /^[0-9A-Za-z]{6,20}$/],
          texts: ['6～20个字符', '可由大小写字母或数字组成']
        },
        repwd: {
          zero: '请输入确认密码'
        }
      },
      username: ''
    }
  },
  computed: {
    ...mapState({
      mobile: state => state.user.mobile
    }),
    computedMobile () {
      return this.mobileError.status && this.codeError.status
    },
    computedName () {
      return this.passwordError.status && this.repwdError.status
    },
    ableSendCode () {
      return this.mobileError.status && !this.isSend && this.forgetForm.imgVerifyCode !== ''
    },
    validateText () {
      return this.time > 0 ? this.time + 's' : '获取验证码'
    }
  },
  methods: {
    // 失去焦点验证方法
    blurValidateMethod (event, type) {
      let value = event.target.value
      this.validateMethod(value, type)
    },
    // 验证表单字段
    validateMethod (value, type) {
      // debugger
      let strategy = this.strategy
      let error = type + 'Error'
      let zero = strategy[type]['zero']
      let rules = strategy[type]['rules']
      let texts = strategy[type]['texts']
      this[error].text = []
      if (value.length < 1) {
        this[error].status = false
        !zero ? this[error].text.push() : this[error].text.push(zero)
        return false
      }
      this[error].status = true
      // 不存在 rules
      if (!rules) return
      for (let i = 0; i < rules.length; i++) {
        if (!rules[i].test(value)) {
          this[error].status = false
          this[error].text.push(texts[i])
        }
      }
    },
    // 手机验证接口
    async fetchMobileValidate (mobile, type, code) {
      let res = await mobileValidate(mobile, type, code)
      return res
    },
    // registerMobile 手机号码 下一步
    forgetMobile () {
      if (!this.mobileError.status || !this.codeError.status) {
        return false // 阻止表单提交
      }
      this.fetchMobileValidate(this.forgetForm.mobile, 3, this.forgetForm.code).then((res, rej) => {
        if (res.data.resultCode === 4008) {
          this.codeError.status = false
          this.codeError.text.push(res.data.resultMsg)
          this.$refs.refcode.focus()
        }
        if (res.data.resultCode === 6000) {
          this.mobileError.status = false
          this.mobileError.text.push(res.data.resultMsg)
        }
        if (res.data.resultCode === 2000) {
          this.forgetStage = 'two'
        }
      })
    },
    // 检测确认密码
    validateRePwd (event) {
      let value = event.target.value
      this.repwdError.text = []
      if (!this.forgetForm.repwd) {
        this.repwdError.status = false
        this.repwdError.text.push('请先输入密码')
        return
      }
      if (!value) {
        this.repwdError.status = false
        this.repwdError.text.push('请再次输入密码')
        return
      }
      if (value !== this.forgetForm.password) {
        this.repwdError.status = false
        this.repwdError.text.push('两次密码不一样')
        return
      }
      this.repwdError.status = true
    },
    // 提交新密码
    pwSubmit () {
      this.validateMethod(this.forgetForm.password, 'password')
      this.validateMethod(this.forgetForm.repwd, 'repwd')
      if (this.forgetForm.password && !this.forgetForm.repwd) {
        return false
      }
      this.fetchforget().then((res) => {
        if (res.data.resultCode && res.data.resultCode === 2000) {
          res = res.data
          this.reloadPW_succeed = true
        } else {
          this.$message({
            message: res.data.resultMsg,
            type: 'error'
          })
        }
      })
    },

    // 密码重置接口
    async fetchforget () {
      let mobile = this.forgetForm.mobile || undefined
      let pass = this.forgetForm.password || undefined
      let rePass = this.forgetForm.repwd || undefined
      let code = this.forgetForm.code || undefined
      let res = await reloadPW(mobile, pass, rePass, code) // 提交新密码
      return res
    },
    // 获取图形验证码
    async verifyImage () {
      let res = await verifyImage()
      if (res.status === 200) {
        var windowUrl = window.URL || window.webkitURL // 处理浏览器兼容性
        this.codeImg = windowUrl.createObjectURL(res.data)
      }
    },
    // 发送短信验证码
    async getCode () {
      // this.time = 60
      if (this.time !== 0) {
        return
      }
      let res = await sendCode(this.forgetForm.mobile, 3, this.forgetForm.imgVerifyCode)
      if (res.data.resultCode && res.data.resultCode !== 2000) {
        this.verifyImage() // 重新获取验证码
        this.$message({
          message: res.data.resultMsg,
          type: 'error'
        })
        if (res.data.resultCode === 6000) {
          this.$refs.mobile.focus()
        }
      } else {
        this.time = 60
      }
    }
  },
  mounted () {
    this.verifyImage()
  },
  watch: {
    time (newV, oldV) {
      let t
      if (newV <= 0) {
        clearTimeout(t)
        this.time = 0
        this.isSend = false
      } else {
        this.isSend = true
        t = setTimeout(() => {
          this.time--
        }, 1000)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  .register_box{
    margin-top: 45px;
    margin-bottom: 60px;
  }
  .step_box{
    width: 70%;
    margin: 0 auto;
  }
  .form-box{
    width: 370px;
    margin: 80px auto 0 auto;
    .form-span{
      line-height: 2.5;
    }
    .form-input{
      height: 50px;
      margin-bottom: 19px;
    }
  }
  .form-item{
    position: relative;
    .error{
      position: absolute;
      left: 380px;
      width: 100%;
      top: 20px;
      i{
        margin-right: 8px;
      }
    }
  }
  .invite-person{
    text-align: center;
    margin-bottom: 30px;
    .title{
      font-size: 14px;
      color: #bcbcbc;
    }
    .invite-name{
      font-size: 16px;
    }
  }
  .forms{
    background: #ffffff;
    // box-shadow: 0 0px 5px 2px rgba(0, 0, 0, 0.1);
    border-radius: 2px;
    margin-top: 20px;
    padding-bottom: 80px;
  }
  .logo_img_box{
    padding-top: 100px;
    text-align: center;
    .logo_img{
      display: inline-block;
      width: 250px;
      & > img{
        width: 100%;
      }
    }
  }
  .memberTit{
    font-size: 18px;
    color: #FFC400;
    padding-bottom: 80px;
    padding-top: 20px;
  }
  .form_box{
    width: 350px;
    margin: 0 auto 30px;
  }
  .validate-box{
    position: relative;
    .valicode-item{
      position: absolute;
      right: 2px;
      top: 1px;
    }
  }
  .valiCode{
    width: 122px;
    height: 50px;
    border: none;
    line-height: 24px;
    text-align: center;
    padding: 12px 4px;
    font-size:14px;
    color:#333333;
    background-color: #FFC400;
    cursor:pointer;
    &.disabled {
      color:#bdbdbd;
      background-color: #f0f0f0;
    }
  }
  .imgCode{
    height: 38px;
    margin: 0 -20px;
    width: 125px;
    overflow: hidden;
    cursor: pointer;
    &> img{
      width: 100%;
      height: 100%;
    }
  }
  .sureBtn{
    display: inline-block;
    cursor: pointer;
    color: #BBBBBB;
    background: #E6E6E6;
    font-size: 16px;
    width: 100%;
    height: 50px;
    text-align: center;
    line-height: 50px;
    margin-top: 22px;
    border: none;
    &.active{
      background: #FFE100;
      color: #303030;
    }
  }
  .btn-large-img{
    position: absolute;
    bottom: 0;
    width: 100%;
    display: inline-block;
    left: 0;
    background: rgba(0,0,0,0.5);
    padding: 10px 0;
    font-size: 12px;
    color: #fff;
    cursor: pointer;
    transform: translateY(35px);
    transition: transform 0.5s linear;
  }
  .mar-bt12{
    margin-bottom: 12px;
  }
  .avatar-uploader {
      width: 178px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      &:hover{
        border-color: #409EFF;
      }
    }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader:hover  .btn-large-img{
    transform: translateY(0)
  }
  .enlargeimg-box{
    width: 500px;
    height: 500px;
    z-index: 2001;
    transform: translate(-50%, -50%);
    position: absolute;
    top: 50%;
    left: 50%;
    img{
      width: 100%;
    }
    .enlargeimg-inner{
      position:relative;
      .close{
        position: absolute;
        cursor: pointer;
        top: -16px;
        right: -23px;
        font-size: 23px;
        color: #fff;
      }
    }
  }
  .error{
    color: #ff0000;
    font-size: 14px;
    .B-error{
      font-size:12px;
      color: #6c6b6b;
      padding-left: 20px;
    }
  }
  .v-modal{
    opacity: 0.7!important;
  }
</style>
